from backend.cews.models import (Log, Equipment, EquipmentLevelRelation)
import json
from django.db.models import Q


def create_asset_relation(eq_class, lv1,lv2,lv3,lv4,lv5=''):

    if not Equipment.objects.filter(equipment_class=eq_class).exists():
        raise ValueError("Equipment class not exists")

    e = Equipment.objects.get(equipment_class=eq_class)

    r = EquipmentLevelRelation(
        equipment = e,
        lv1=lv1,
        lv2=lv2,
        lv3=lv3,
        lv4=lv4,
        lv5=lv5,
    )
    r.save()

    return True

def update_asset_relation(id,eq_class, lv1,lv2,lv3,lv4,lv5=''):

    if not Equipment.objects.filter(equipment_class=eq_class).exists():
        raise ValueError("Equipment class not exists")
    
    if not EquipmentLevelRelation.objects.filter(pk=id).exists():
        raise ValueError("Asset relation not exists")
    
    e = Equipment.objects.get(equipment_class=eq_class)

    r = EquipmentLevelRelation.objects.get(pk=id)
    r.equipment = e
    r.lv1 = lv1
    r.lv2 = lv2
    r.lv3 = lv3
    r.lv4 = lv4
    r.lv5 = lv5
    r.save()

    return True

def soft_delete_asset_relation(id, user):

    if not user.has_perm('cews.delete_equipmentlevelrelation'):
        raise ValueError('User has no permission to delete asset relation.')

    e = EquipmentLevelRelation.objects.get(pk=id)
    e.delete()
    # e.deleted = True
    # e.save()

    return True


def import_asset_lv4_relation(lv4, lv5=''):
    if not EquipmentLevelRelation.objects.filter(lv4=lv4, lv5=lv5).exists():
        raise ValueError("The relation is not define")
    r = EquipmentLevelRelation.objects.get(lv4=lv4, lv5=lv5, deleted=False)

    return r

def import_asset_lv5_relation(lv5):
    if not EquipmentLevelRelation.objects.filter(lv5=lv5).exists():
        raise ValueError("The relation is not define")
    
    r = EquipmentLevelRelation.objects.get(lv5=lv5, deleted=False)

    return r

def import_asset_eq_relation(equipment_class):

    eq = Equipment.objects.get(equipment_class=equipment_class)

    if not EquipmentLevelRelation.objects.filter(equipment=eq).exists():
        raise ValueError("The relation is not define")
    
    r = EquipmentLevelRelation.objects.get(equipment=eq, deleted=False)

    return r